<template>
    <div class="basic step-box">
        <el-form
            ref="ruleFormRef"
            :disabled="pageType === 'look'"
            :rules="rules"
            :model="rulesform"
            class="ruleForm"
            @submit.prevent>
            <el-form-item label="使用群" prop="name" label-width="70px">
                <div class="tableList">
                    <div class="table_header">
                        <el-button class="addBtn" @click="openGroup">添加群聊 </el-button>
                        <el-button
                            :disabled="useGroupData.length <= 0"
                            @click="groupBtn(2, '455px', '批量设置群活码人数上限')"
                            >批量设置群活码人数上限
                        </el-button>
                        <el-button :disabled="useGroupData.length <= 0" @click="groupBtn(3, '455px', '批量删除')"
                            >批量删除</el-button
                        >
                    </div>
                </div>
                <el-table
                    ref="multipleTableRef"
                    max-height="550"
                    :data="changeList"
                    stripe
                    style="width: 1220px"
                    class="tableData"
                    :header-cell-style="{ background: '#F9F9F9', color: '#33302D' }"
                    @selection-change="selectUseGroup">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="名称" prop="picture" width="150">
                        <template #default="{ row }">
                            <div style="display: flex; align-items: center">
                                <!-- {{scope.row.avatar}} -->
                                <img width="36" height="36" style="border-radius: 4px" :src="row.avatar" alt="" />
                                <el-tooltip effect="dark" :content="row.name" placement="top-start">
                                    <p class="group_name">{{ row.name }}</p>
                                </el-tooltip>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="manager" label="群主" width="250">
                        <template #default="scope">
                            <div v-if="scope.row.manager.name">
                                <span v-if="scope.row.manager.name"> {{ scope.row.manager.name }}/</span>
                                <span v-else>-/</span>
                                <span v-for="(item, index) in scope.row.manager.department_name" :key="index"
                                    >{{ item.name ? item.name : '-'
                                    }}<span v-if="scope.row.manager.department_name.length - 1 != index">，</span>
                                </span>
                            </div>
                            <div v-else>暂无</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="群成员" prop="members_num"> </el-table-column>
                    <el-table-column prop="created_at" label="创建时间" width="200">
                        <template #default="scope">
                            <span>
                                {{ DFormat(Date.parse(scope.row.created_at), 'yyyy-MM-dd hh:mm:ss') }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="350" fixed="right">
                        <template #default="{ row, $index }">
                            <div class="operation">
                                <p>群活码人数上限</p>
                                <el-input-number
                                    v-model="row.limit"
                                    size="small"
                                    class="mx-4"
                                    :min="1"
                                    :max="200"
                                    controls-position="right"
                                    @change="changeLimit(row.limit, $index)" />
                                <!-- <el-input class="upper" oninput="value=value.replace(/[^0-9.]/g,'')" size="small" v-model.trim="row.limit" @input="changeLimit(row.limit, $index)" clearable /> -->
                                <span class="delGroup" @click="delGroup($index)">删除</span>
                            </div>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <div style="height: 422px; margin-top: 100px" class="emty">
                            <img class="emty_img" src="@/assets/noData.png" alt="" />
                            <div style="margin: -30px 35px 0 0">
                                {{ tableList.length || '暂无数据' }}
                            </div>
                        </div>
                    </template>
                </el-table>
            </el-form-item>
            <el-form-item label="客户标签" prop="tag_flag" label-width="80px" class="m_t">
                <el-switch v-model="form.tag_flag" :active-value="1" :inactive-value="2" />
            </el-form-item>
            <el-form-item v-show="form.tag_flag === 1" label-width="80px">
                <div>
                    <el-tag
                        v-for="tag in AllCusTag"
                        :key="tag.id"
                        class="cusTag"
                        type="warning"
                        :closable="!(pageType === 'look')"
                        :disable-transitions="false"
                        @close="handleClose(tag)">
                        {{ tag.name }}
                    </el-tag>
                </div>
                <el-button class="sleTag" @click="openBatchLabel('formData')">选择标签</el-button>
            </el-form-item>
        </el-form>
        <!-- <div class="btns">
            <el-button class="step" @click="prev">上一步</el-button>
            <el-button v-if="pageType != 'look'" class="next" @click="saveWel">保存</el-button>
            <el-button v-else class="next" @click="saveWel">返回</el-button>
        </div> -->
    </div>
    <Dialog :app-dialog="appDialog">
        <div v-if="dialogType == 2">
            <div class="batchOperation">
                <p>群活码人数上限</p>
                <el-input-number
                    v-model="AllCusLimit"
                    style="width: 130px"
                    class="mx-4 batchUpper"
                    :min="0"
                    :max="200"
                    controls-position="right"
                    @blur="maxNum" />
            </div>
        </div>
        <div v-else-if="dialogType == 3">
            <div class="batchOperation">确定要删除所选中的数据吗？</div>
        </div>
    </Dialog>
    <!-- 批量标签弹框 -->
    <BatchLabel ref="BatchLabelRef" @save="getTagsFun" />
    <ZWDepart ref="DepartRef" @submit="getDepart" />
    <GroupChart ref="GroupChartRef" @submit="getGroup" />
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue';
import Dialog from '@/components/Dialog.vue';
import GroupChart from '@/components/chart/GroupChart.vue';
import ZWPagination from '@/components/ZWPagination.vue';
import BatchLabel from '@/components/BatchLabel.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import router from '@/router';
import { useStore } from '@/store';
import { DFormat, getSetionId } from '@/utils/utils';
import { ElMessage } from 'element-plus';
import { addGroupCode, editGroupCode, lookGroupCode } from '@/api/smartMarketing/drainage/channelCode/index';
import { useRoute } from 'vue-router';

const DepartRef = ref(null);
const creators = ref([]);
const props = withDefaults(
    defineProps<{
        pageType: string;
        pageId: any;
    }>(),
    { pageType: 'new', pageId: '' }
);
const emit = defineEmits(['next', 'prev']);

const store = useStore();
const searchSelectRef = ref<null | HTMLElement>(null); // 选择标签弹框
const BatchLabelRef = ref(null);

const tableList = ref([]); // 选中的群聊数据
const changeList = ref([]); //选中展示的数据
const tableData = ref([]); // 群聊列表数据
const groupTable = ref(); // 选择群聊 table
const AllCusTag = ref([]); //选中的客户标签
const dialogTitle = ref(''); // 弹框的 title
const dialogType = ref(1); // 弹框类型: 1 选择群聊, 2 批量设置上限, 3 批量删除
const dialogWidth = ref('1200px'); // 弹框的宽度
const AllCusLimit = ref(1); // 批量设置上限数值
const useGroupData = ref([]); //选择使用群
const useGroup = reactive([]); // 使用群 id
const maximum = ref(5); // 最多只能选择 5个群聊
const isNext = ref(true); //是否为下一步
const route = useRoute();
const GroupChartRef = ref(null);
const groupchat_ids = ref([]);
const id = ref(route.query.id);
const creators2 = ref([]);
// 选择客户标签
const tabsList = ref([]);
const selectData = ref([]);
const chooseTableData = ref([]);
const isChangeAll = ref(false);

const rulesform = reactive({ name: '1' });

// 分页基础信息
const pageInfo = reactive({
    page_size: 15,
    page: 1,
    is_qw_group: '-1'
});
const form = ref({
    tag_flag: 1,
    tag_list: []
});
const formInline = reactive({
    group_leader: '',
    group_name: ''
});
const labelObj = {
    type: '', //当前打开选择标签是哪个类型
    data: [] //选中标签的数据存储
};
const rules = reactive({
    name: [
        {
            required: true,
            message: '',
            trigger: ''
        }
    ],
    tag_flag: [{ required: true, message: '', trigger: 'blur' }]
});

const openGroup = () => {
    GroupChartRef.value.appDialog.visible = true;
    GroupChartRef.value.echoDataId = getSetionId('group_id', changeList.value);
};
const filterNewData = (data: any) => {
    let res: any = [];
    const arr = getSetionId('group_id', changeList.value);
    res = data.filter((i: any) => !arr.includes(i.group_id));
    return res;
};
const getGroup = (res: any) => {
    const tableArr = Array.from(new Set([...filterNewData(res)]));
    const arr: any[] = [],
        len = creators2.value.length;
    if (tableArr.length > 0) {
        tableArr.map((item: any) => {
            item.limit = 200;
            changeList.value.push(item);
            useGroup.push({ groupchat_id: item.group_id, limit: item.limit });
        });
        tableArr.forEach((item: any) => {
            arr.push({
                owner_work_user_id: item.group_id
            });
        });
    }
    creators2.value = arr;
    groupchat_ids.value = getSetionId('owner_work_user_id', creators2.value);
};
const delGroup = (index: number) => {
    changeList.value.splice(index, 1);
    useGroup.splice(index, 1);
    groupchat_ids.value.splice(index, 1);
};
// 表格操作按钮
const groupBtn = (n: number, w: string, t: string) => {
    dialogType.value = n;
    dialogWidth.value = w;
    dialogTitle.value = t;
    appDialog.visible = true;
};
// 分页信息
const page = (page: any) => {
    pageInfo.page = page.page;
    pageInfo.page_size = page.page_size;
};
// 选择使用群
const selectUseGroup = (data: any) => {
    const arr = [];
    data.map((item: any) => {
        arr.push(item);
    });
    useGroupData.value = arr;
};
// 选择群聊
const selectGroup = (data: any) => {
    if (data.length > maximum.value) {
        selectData.value = data;
        const del_row = data.shift();
        groupTable.value.toggleRowSelection(del_row, false);
    } else {
        tableList.value = data;
    }
};
const getRowKeys = (row: any) => {
    return row.id;
};
const maxNum = (e: any) => {
    if (+e.target.value > 200) {
        ElMessage.warning('群活码人数上限最多200');
        AllCusLimit.value = 200;
    }
};

// 清空查询表单
const onClear = () => {
    formInline.group_leader = '';
    formInline.group_name = '';
    pageInfo.page = 1;
    pageInfo.page_size = 15;
};
// table 表单的全选
const selectAll = (data: any) => {
    isChangeAll.value = true;
    if (data.length > 5) {
        data.length = 5;
    }
};
// 设置活码上限
const changeLimit = (val: any, num: number) => {
    useGroup[num].limit = +val;
};
const changeLabel = (value: any) => {
    tabsList.value = tabsList.value.filter((item: any) => item.id == value);
};
// 打开选择标签弹框
const openBatchLabel = (type: string) => {
    labelObj.type = type;
    BatchLabelRef.value.dialogData.labelChooseType = type == 'formData' ? 2 : 1;
    BatchLabelRef.value.hasConditiion = false;
    BatchLabelRef.value.chooseDataArr = [];
    if (tabsList.value.length > 0 && type == 'formData') {
        BatchLabelRef.value.chooseDataArr = AllCusTag.value;
        // BatchLabelRef.value.chooseDataArr = form.value.tag_list
    }
    BatchLabelRef.value.dialogVisible = true;
};
// 获取当前选中的标签数据
const getTagsFun = (val: any) => {
    if (labelObj.type == 'formData') {
        AllCusTag.value = [...val.data];
        tabsList.value = [...val.data];
        form.value.tag_list = val.idList;
    }
};
// 获取客户标签
const getTags = (data: any) => {
    AllCusTag.value = data;
    form.value.tag_list = getSetionId('id', data);
};
// 移除客户标签
const handleClose = (val: any) => {
    const i = form.value.tag_list.findIndex((n: any) => n == val.id);
    AllCusTag.value.splice(AllCusTag.value.indexOf(val), 1);
    form.value.tag_list.splice(i, 1);
};
// 弹框取消
const cancelHandel = () => {
    appDialog.visible = false;
    AllCusLimit.value = 0;
};
// 弹框确认
const submitHandel = () => {
    if (dialogType.value == 1) {
        tableList.value.map((item: any) => {
            item.limit = null;
            changeList.value.push(item);
            useGroup.push({ groupchat_id: item.group_id, limit: item.limit });
        });
    } else if (dialogType.value == 2) {
        useGroupData.value.map((item: any) => {
            const i = changeList.value.findIndex((u: any) => u.group_id == item.group_id);
            if (i != -1) {
                changeList.value[i].limit = changeList.value[i].limit - 0 + +AllCusLimit.value;
                changeList.value[i].limit = +AllCusLimit.value;
                useGroup[i].limit = +AllCusLimit.value;
            }
        });
    } else if (dialogType.value == 3) {
        useGroupData.value.map((item: any) => {
            const i = changeList.value.findIndex((u: any) => u.group_id == item.group_id);
            changeList.value.splice(i, 1);
            useGroup.splice(i, 1);
        });
        groupchat_ids.value = useGroupData.value.map((item: any) => item.group_id);
    }
    cancelHandel();
};
const saveWel = () => {
    if (next()) {
        const data = store.state.newCode.newCode;
        if (props.pageType === 'edit') {
            data.activity_id = id.value;
        }
        const params = {
            ...form.value,
            groupchat: useGroup
        };
        const result = Object.assign(params, data);
        const param = { group_id: result.group_id };
        // return
        if (props.pageType == 'look') {
            router.push({ name: 'SMART_MARKETING_DRAINAGE_GROUP_CODE', params: param, query: param });
        } else if (props.pageType == 'edit') {
            editGroupCode(result)
                .then((res: any) => {
                    ElMessage.success('保存成功');
                    router.push({
                        name: 'SMART_MARKETING_DRAINAGE_GROUP_CODE',
                        params: param,
                        query: param
                    });
                })
                .catch((err: any) => {
                    ElMessage.error('保存失败');
                    router.push({
                        name: 'SMART_MARKETING_DRAINAGE_GROUP_CODE',
                        params: param,
                        query: param
                    });
                });
        } else {
            addGroupCode(result)
                .then((res: any) => {
                    ElMessage.success('保存成功');
                    router.push({
                        name: 'SMART_MARKETING_DRAINAGE_GROUP_CODE',
                        params: param,
                        query: param
                    });
                })
                .catch((err: any) => {
                    // ElMessage.error('保存失败')
                    router.push({
                        name: 'SMART_MARKETING_DRAINAGE_GROUP_CODE',
                        params: param,
                        query: param
                    });
                });
        }
    }
};
const getLook = () => {
    const v = {
        activity_id: props.pageId,
        step: 2
    };
    if (props.pageType === 'look' || props.pageType === 'edit') {
        lookGroupCode(v).then((res: any) => {
            isNext.value = false;
            maximum.value = maximum.value - res.groupchat.length;
            res.groupchat.map((item: any) => {
                changeList.value.push({
                    group_id: item.groupchat_id,
                    manager: { name: item.owner_username, department_name: item.department_list },
                    members_num: item.member_nums,
                    created_at: item.created_at,
                    limit: item.limit,
                    avatar: item.avatar,
                    name: item.name,
                    owner_username: item.owner_username
                });
                groupchat_ids.value.push(item.groupchat_id);
                useGroup.push({ groupchat_id: item.groupchat_id, limit: item.limit });
            });
            res.tag_list.map((item: any) => {
                AllCusTag.value.push(item);
                form.value.tag_list.push(item.id);
            });
            tabsList.value = res.tag_list;
            form.value.tag_flag = res.tag_flag;
        });
    }
};
// 下一步
const next = () => {
    if (useGroup.length <= 0 && useGroupData.value.length <= 0) {
        ElMessage.warning('请选择使用群');
        return false;
    } else {
        const arr = [];
        useGroup.map((item: any) => {
            if (item.limit == null || item.limit == 0) {
                arr.push(1);
            }
        });
        if (arr.length > 0) {
            ElMessage.warning('请设置群上限');
            return false;
        }
    }
    if (form.value.tag_list.length <= 0 && form.value.tag_flag == 1) {
        ElMessage.warning('请选择客户标签');
        return false;
    } else {
        return true;
    }
};
// 上一步
const prev = () => {
    emit('prev');
};
const getDepart = (res: any) => {
    creators.value = res;
    formInline.group_leader = getSetionId('id', creators.value);
    DepartRef.value.departVisble = false;
};
//删除选择的创建人
const changedept = (res: any) => {
    const removeDepart = creators.value.find((item: any) => !res.includes(item.id));
    creators.value = creators.value.filter((data: any) => res.includes(data.id));
    formInline.group_leader = res;
    DepartRef.value.removeItem(removeDepart);
};
//打开员工弹窗
const opendept = () => {
    DepartRef.value.selectedMember = creators.value;
    DepartRef.value.departVisble = true;
    DepartRef.value.title = '选择群组/创建人';
};
// 弹框配置项
const appDialog = reactive({
    visible: false,
    title: dialogTitle,
    width: dialogWidth,
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [] // 传递进来选中的数据
});
// watch(
//   () => selectData.value,
//   (nVal) => {
//     if (nVal.length >= 5) {
//       ElMessage.warning('最多可以选择五个群聊！')
//     }
//   },
//   { deep: true }
// )
watch(
    () => form.value.tag_flag,
    val => {
        if (val == 2) rules.tag_flag[0].required = false;
        else rules.tag_flag[0].required = true;
    }
);
defineExpose({
    getLook,
    isNext,
    prev,
    saveWel
});
</script>

<style lang="scss" scoped>
.basic {
    background-color: #fff;

    .ruleForm {
        .tableList {
            max-width: 1220px;

            .table_header {
                padding: 7px 10px;
                border: 1px solid #eaeaea;
                border-radius: 4px 4px 0 0;

                .addBtn {
                    color: #fff;
                    background: #ff6b00;
                    border: 1px solid #ff6b00;
                }
            }
        }

        .tableData {
            background: #fff;
            box-sizing: border-box;
            border: 1px solid #eaeaea;
        }

        .operation {
            display: flex;
            align-items: center;
            justify-content: space-around;

            :deep .upper {
                width: 171px;
                margin-left: 11px;
            }

            .delGroup {
                cursor: pointer;
            }
        }

        :deep .cusTag {
            height: 22px;
            line-height: 20px;
            font-size: 14px;
            color: #ff6b00;
            margin-right: 6px;
            border: 1px solid #ffc69e;
            background-color: #fffaf9;
        }

        :deep .el-form-item {
            margin-bottom: 0;
        }
    }

    .btns {
        width: 100%;
        background: #fff;
        display: flex;
        justify-content: center;
        position: absolute;
        padding-top: 10px;
        bottom: 0;
        box-sizing: border-box;

        .step {
            color: #ff6b00;
            border: 1px solid #ff6b00;
        }

        .next {
            color: #fff;
            border: none;
            background: #ff6b00;
        }
    }
}

.gc-header {
    margin-bottom: 20px;
    background-color: #f9f9f9;

    .form-inline {
        justify-content: space-between;

        .el-form-item {
            margin-bottom: 0;
            padding: 18px;
        }

        display: flex;
        align-items: center;
    }
}

.btn-wrap {
    display: flex;
}

.batchOperation {
    display: flex;
    align-items: center;
    padding: 33px 0 41px;

    :deep .batchUpper {
        width: 171px;
        margin-left: 11px;
    }
}

.m_t {
    margin-top: 14px;
}

.group_name {
    width: 100px;
    color: #33302d;
    font-size: 14px;
    margin-left: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>
